package com.jinbooks.web.monitor.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinbooks.authn.annotation.CurrentUser;
import com.jinbooks.authn.session.SessionManager;
import com.jinbooks.entity.Message;
import com.jinbooks.entity.access.SessionList;
import com.jinbooks.entity.access.dto.SessionListPageDto;
import com.jinbooks.entity.idm.UserInfo;
import com.jinbooks.persistence.service.SessionListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 在线用户监控控制器
 *
 * @author your-name
 */
@RestController
@RequestMapping("/monitor/online")
public class OnlineController {
    private static final Logger logger = LoggerFactory.getLogger(OnlineController.class);

    @Autowired
    private SessionListService sessionListService;

    @Autowired
    private SessionManager sessionManager;

    /**
     * 获取在线用户列表
     *
     * @param dto 分页参数
     * @param currentUser 当前用户
     * @return 在线用户列表
     */
    @GetMapping("/list")
    public Message<Page<SessionList>> list(
            @ParameterObject SessionListPageDto dto,
            @CurrentUser UserInfo currentUser) {
        logger.debug("monitor/online/list {}", dto);

        //dto.setBookId(currentUser.getWorkspaceId());
        dto.setUserId(currentUser.getId());
        Page<SessionList> page = sessionListService.pageList(dto);
        return new Message<>(page);
    }

    /**
     * 强制用户下线
     *
     * @param tokenId 会话ID
     * @param currentUser 当前用户
     * @return 操作结果
     */
    @DeleteMapping("/{tokenId}")
    public Message<String> forceLogout(
            @PathVariable String tokenId,
            @CurrentUser UserInfo currentUser) {
        logger.debug("monitor/online/{} by user: {}", tokenId, currentUser.getUsername());

        try {
            // 不允许用户终止自己的会话
            if (currentUser.getSessionId().contains(tokenId)) {
                return Message.failed("不能终止自己的会话");
            }

            // 终止指定会话
            sessionManager.terminate(tokenId, currentUser.getId(), currentUser.getUsername());
            logger.info("用户 {} 的会话 {} 已被管理员 {} 终止",
                    tokenId, currentUser.getUsername(), currentUser.getUsername());
            return Message.ok("会话已终止");
        } catch (Exception e) {
            logger.error("终止会话时发生错误", e);
            return Message.failed("终止会话失败: " + e.getMessage());
        }
    }
}